<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\BaseController;
use App\Interfaces\MenuInterface;
use App\Interfaces\RoleInterface;
use App\Interfaces\UserInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;

class AuthController extends BaseController
{
    protected UserInterface $user;

    protected MenuInterface $menu;

    protected RoleInterface $role;

    public function __construct(UserInterface $user, RoleInterface $role,MenuInterface $menu)
    {
        $this->user = $user;
        $this->role = $role;
        $this->menu = $menu;
    }

    public function userInfo(Request $request): JsonResponse
    {
        $user = $request->get('userInfo');

        if(!$user){
            return $this->apiResult(['code'=>1,'message'=>'你还未登录！']);
        }

        $roleIds = json_decode($user['roles']);

        $roles = $this->role->getUserRoles($roleIds);

        $menuIds = array();
        foreach ($roles as $value){
            $menuIds = Arr::collapse([$menuIds,json_decode($value->menuId)]);
        }

        $menus = $this->menu->getUserMenu($menuIds);

        $user['authorities'] = $menus;

        $user['roles'] = $roles;

        return $this->apiResult(['code'=>0,'data'=>$user,'message'=>'SUCCESS']);
    }

    /**
     * 修改密码
     * @param Request $request
     * @return JsonResponse
     */
    public function editPassword(Request $request): JsonResponse
    {
        $oldPassword = $request->input('oldPassword');
        $password = $request->input('password');
        $password2 = $request->input('password2');
        $basePassword = $request->get('userInfo')->password;
        $check = Hash::check($oldPassword,$basePassword);
        if (!$check){
            return $this->apiResult(['code'=>1,'message'=>'原密码输入错误！']);
        }
        if ($password != $password2){
            return $this->apiResult(['code'=>1,'message'=>'两次密码不一致！']);
        }

        $data = array(
            'userId'=>$request->get('userInfo')->userId,
            'password'=>bcrypt($password)
        );
        $res = $this->user->updateUser($data);
        if(!$res){
            return $this->apiResult(['code'=>1,'message'=>'密码修改失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'密码修改成功！']);
    }
}
